/**
 * Created by Levil on 2015/3/17.
 */

(function(){
    jsb.fileUtils.addSearchPath("src/");
//    jsb.fileUtils.addSearchPath("res/");

    var Module = {};

    var ModuleStates = {};
    var EnumState = {
        Loading : 1,
        Loaded: 2
    }

    var ModuleProxies = {};

    dumpModuleInfo = function() {
        cc.log("******************************[Module]*********************************");
        for(var key in Module){
            var info = cc.formatStr("[%s]", key);
            if (ModuleStates[key] === EnumState.Loading){
                info += " is loading";
            }
            cc.log(info);
        }
        cc.log("***********************************************************************");
    }


    load = function(name, func){
        ModuleStates[name] = EnumState.Loading;

        var module = func();
        Module[name] = module;

        var proxy = ModuleProxies[name];
        proxy.module = module;
        proxy.prototype = module.prototype;
        proxy.__proto__ = module;
    }

    include = function(name){
        var module = Module[name];
        var state = ModuleStates[name];

        if (ModuleStates[name] === EnumState.Loaded){
            // the module is loaded, return the proxy
            return ModuleProxies[name];
        }
        else{
            // an interface function (use this function as a constructor of cc.Class or derived class)
            var proxy = ModuleProxies[name] || function(){
                if (typeof(arguments.callee.module) === "function")
                    arguments.callee.module.apply(this, arguments);
                else
                    cc.warn("[Module] The module [%s] is not valid.", name);
            }
            ModuleProxies[name] = proxy;

            if (ModuleStates[name] === EnumState.Loading){
                // the module is loading, return the proxy function
                return proxy;
            }
            else{   // Module is not loading or loaded
                var path = name + ".js";
                cc.log("[Module] Try to load module [%s] from file [%s]", name, path);
                ModuleStates[name] = EnumState.Loading;
                require(path);
                ModuleStates[name] = EnumState.Loaded;

                proxy.module = Module[name];
                proxy.prototype = Module[name].prototype;
                proxy.__proto__ = Module[name];

                return proxy;
            }
        }
    }

})()